package com.example.user.view;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.databinding.DataBindingUtil;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.RadioGroup;

import com.example.common.component.MyToast;
import com.example.user.R;
import com.example.user.databinding.UserModifyInfoFragmentBinding;
import com.example.user.viewmodel.UserModifyInfoViewModel;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class UserModifyInfoFragment extends Fragment {

    private static final String TAG = "UserModifyInfoFragment";
    private UserModifyInfoViewModel mViewModel;
    private UserModifyInfoFragmentBinding binding;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.user_modify_info_fragment, container, false);
        mViewModel = new ViewModelProvider(this).get(UserModifyInfoViewModel.class);

        binding.setData(mViewModel.getUserDetail());
        binding.setLifecycleOwner(getViewLifecycleOwner());

        View view = binding.getRoot();

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            //获取用户主页传入的数据并处理
            Bundle bundle = getArguments();
            mViewModel.dealBundle(bundle);
        }
        //根据gender判断radioGroup的显示
        if (mViewModel.getGender() == 0) {
            binding.radioGroup.check(binding.userModifySexSecretRadioButton.getId());
        } else if (mViewModel.getGender() == 1) {
            binding.radioGroup.check(binding.userModifySexMaleRadioButton.getId());
        } else {
            binding.radioGroup.check(binding.userModifySexFemaleRadioButton.getId());
        }

        //初始化设置
        mViewModel.getIsUpDetail().setValue(false);

        //点击头像打开相册
        binding.userIvAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //动态获取应用存储权限
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_PERMISSION_STORAGE = 100;
                    String[] permissions = {
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    };

                    for (String str : permissions) {
                        if (requireActivity().checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            requireActivity().requestPermissions(permissions, REQUEST_CODE_PERMISSION_STORAGE);
                            return;
                        }
                    }
                }
                //打开相册
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1);
            }
        });

        //根据用户更改radioGroup来更改gender属性
        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == binding.userModifySexMaleRadioButton.getId()) {
                    mViewModel.setGender(1);
                } else if (checkedId == binding.userModifySexFemaleRadioButton.getId()) {
                    mViewModel.setGender(2);
                } else {
                    mViewModel.setGender(0);
                }
            }
        });

        //日期
        binding.button3.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            new DatePickerDialog(this.getContext(), new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    String text = String.format(Locale.getDefault(),"%d-%02d-%02d", year, month+1,dayOfMonth);
                    //更改ViewModel的Birthday
                    mViewModel.setBirthday(text);
                    //更改显示框内容
                    binding.userModifyDate.setText(text);
                }
            }
                    , calendar.get(Calendar.YEAR)
                    , calendar.get(Calendar.MONTH)
                    , calendar.get(Calendar.DAY_OF_MONTH)).show();
        });

        //点击修改
        binding.userModifyInfoBtChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击修改用户资料
                mViewModel.upLoadDetailChange();
            }
        });

        //监听提示信息
        mViewModel.getRemainMsg().observe(requireActivity(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                MyToast.showMyToast(requireContext(),s,1);
            }
        });

        //监听修改是否成功，然后跳转
        mViewModel.getIsUpDetail().observe(requireActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    //导航
                    Bundle bundle=new Bundle();
                    bundle.putBoolean("CHANGE",true);

                    NavController navController = Navigation.findNavController(requireView());
                    navController.navigate(R.id.action_userModifyInfoFragment_to_userMyProfileDetailFragment2,
                           bundle);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1 && data != null){
            Uri uri=data.getData();//图片url
            ContentResolver resolver=requireActivity().getContentResolver();

            Cursor cursor=resolver.query(uri,null,null,null,null);
            boolean first=cursor.moveToFirst();
            if(first){
                try {
                    //获取图片地址
                    int columnIndex=cursor.getColumnIndex("_data");
                    String path=cursor.getString(columnIndex);
                    mViewModel.upLoadAvatar(path);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    }
}